<?php
/**
 * Auth Model. Singleton
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Usermanagement Module
 * @subpackage Model
 * @license  New BSD License
 * 
 */
class Models_Usermanagement_Auth extends Zend_Auth_Adapter_DbTable {
	
	/**
	 * name of the DB field to use as login  
	 *
	 * @var string
	 */
	protected $_identityColumn = 'user_login';
	
	/**
	 * name of the DB field to use as password
	 *
	 * @var string
	 */
	protected $_credentialColumn = 'user_password';
	
	/**
	 * Password encryption type
	 *
	 * @var string
	 */
	protected $_credentialTreatment = 'MD5(?) AND user_active =1';
	
	/**
	 * Session to store userdata
	 *
	 * @var Zend_Session_Namespace
	 */
	protected $_session = false;
	
	/**
	 * DB object
	 *
	 * @var Zend_Db
	 */
	protected $_zendDB;
	
	/**
	 * Class instance for Singleton
	 *
	 * @var $this
	 */
	private static $_instance;
	
	/**
	 * Users Model
	 *
	 * @var Models_Usermanagement_Users
	 */
	private static $users;
	
	/**
	 * Constructor
	 *
	 */
	public function __construct() {
		$this->_zendDb = Zend_Registry::get ( 'db' );
		$this->_tableName = TABLE_PREFIX.'users';
		$this->_session = new Zend_Session_Namespace ( 'auth' );
	}
	
	/**
	 * Singleton realization. Call this to get instance of this class
	 *
	 * @return Models_Usermanagement_Auth
	 */
	static public function getInstance() {
		if (null === self::$_instance) {
			self::$_instance = new self ( );
		}
		
		return self::$_instance;
	}
	
	/**
	 * Login 
	 *
	 * @param string $username
	 * @param string $password
	 * @return object
	 */
	public function login($username, $password) {
		
		//var_dump($username);die;
		
		$this->_identity = $username;
		$this->_credential = $password;
		
		return parent::authenticate ();
	}
	
	/**
	 * Saves userdata into session
	 *
	 */
	public function setUserSession() {
		$this->_session->userdata = $this->getResultRowObject ();
	}
	
	/**
	 * Returns userdata from session
	 *
	 * @return Zend_Db_Table_Row
	 */
	public function getUserSession() {
		if ($this->isLoggedIn ()) {
			if (! isset ( self::$users )) {
				self::$users = new Models_Usermanagement_Users ( );
			}
			$this->_session->userdata = self::$users->find ( $this->_session->userdata->user_id )->current ();
			return $this->_session->userdata;
		} else {
			return false;
		}
	}
	
	/**
	 * Checks if user is logged in
	 *
	 * @return bool
	 */
	public function isLoggedIn() {
		if ($this->_session->userdata)
			return true;
		return false;
	}
	
	/**
	 * Performs logout action
	 *
	 */
	public function logout() {
		$this->_session->unsetAll ();
	}
}